(function () {
    "use strict";

    require("./slice-args");
    var defineType = require("./define-type");

    module.exports = defineType(function () {
        this.handlers = {};
    }, {
        handlers: {},

        on: function (name, handler) {
            if (!(handler instanceof Function)) {
                return;
            }

            var handlers = this.handlers[name];
            if (!handlers) {
                handlers = [];
                this.handlers[name] = handlers;
            }

            handlers.push(handler);
        },

        off: function (name, handler) {
            if (arguments.length < 2) {
                delete this.handlers[name];
                return;
            }

            var handlers = this.handlers[name];
            if (!handlers) {
                return;
            }

            var index = handlers.indexOf(handler);
            if (index < 0) {
                return;
            }

            handlers.splice(index, 1);
            if (!handlers.length) {
                delete this.handlers[name];
            }
        },

        trigger: function (name) {
            var handlers = this.handlers[name];
            if (!handlers) {
                return;
            }

            var args = Function.sliceArgs(arguments, 1);
            handlers.forEach(function (handler) {
                handler.apply(this, args);
            }, this);
        }
    });
})();
